package gr.handmademarket.ui.panels;

import static gr.handmademarket.util.CommonStatics.PRODUCTS_PICS_PATH;
import static gr.handmademarket.util.CommonStatics.PRODUCTS_TEMP_PICS_PATH;
import gr.handmademarket.bl.operations.LoadCategoriesOperation;
import gr.handmademarket.bl.operations.SaveProductOperation;
import gr.handmademarket.po.implementations.Product;
import gr.handmademarket.po.implementations.ProductCategory;
import gr.handmademarket.ui.WebHandMadeMarketApplication;
import gr.handmademarket.ui.pages.ProductDetailsPage;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.image.NonCachingImage;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.resource.ContextRelativeResource;

/**
 * the panel used to upload a new product or edit an existing one.
 */
public class UploadProductPanel 
extends Panel{

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * the product.
	 */
	private Product product;
	
	private RequiredTextField<String> nameField = new RequiredTextField<String>("name");
	private TextArea<String> descriptionField = new TextArea<String>("description");
	private RequiredTextField<Double> priceField = new RequiredTextField<Double>("price");
	private DropDownChoice<ProductCategory> categoryCombo;

	private Form<Product> form; 
	private NonCachingImage image;
	private NonCachingImage tempImg;
	
	private List<FileUpload> filesList = new ArrayList<FileUpload>();
	private IModel<List<FileUpload>> filesModel = new CompoundPropertyModel<List<FileUpload>>(filesList);
	private FileUploadField fileUploadField = new FileUploadField("fileUpload" , filesModel);
	
	private AjaxButton saveBtn = new AjaxButton("saveBtn") {
		
		/**
		 * serialVersionUID
		 */
		private static final long serialVersionUID = 1L;
		
		public void onSubmit(AjaxRequestTarget target, Form<?> form1) {
			boolean isNew = product.getCode() == -1;
			SaveProductOperation op = new SaveProductOperation();
			op.setProduct(product);
			op.execute();
			product = op.getProduct();
			if (tempImg != null){
				int tmpCode = isNew ? -1 : product.getCode();
				String tempPath = PRODUCTS_TEMP_PICS_PATH + tmpCode + ".jpg";
				ServletContext context = WebHandMadeMarketApplication.get().getServletContext();
				String realTempPath = context.getRealPath(tempPath);
				String path = PRODUCTS_PICS_PATH + product.getCode() + ".jpg";
				String realPath = context.getRealPath(path);
				File pic = new File(realPath);
				if (pic.exists()){
					pic.delete();
				}
				File tempPic = new File(realTempPath);
				tempPic.renameTo(pic);
			}
			ProductDetailsPage page = new ProductDetailsPage(new Model<Product>(product));
			setResponsePage(page);
		};
	};
	
	private AjaxButton previewBtn = new AjaxButton("previewBtn") {

		/**
		 * serialVersionUID
		 */
		private static final long serialVersionUID = 1L;
		
		@Override
		protected void onSubmit(AjaxRequestTarget target, Form<?> form1) {
			final FileUpload uploadedFile = fileUploadField.getFileUpload();
			if (uploadedFile != null) {
				String path = PRODUCTS_TEMP_PICS_PATH + product.getCode() + ".jpg";
				ServletContext context = WebHandMadeMarketApplication.get().getServletContext();
				String realPath = context.getRealPath(path);
				File newFile = new File(realPath);
				if (newFile.exists()) {
					newFile.delete();
				}
				try {
					newFile.createNewFile();
					uploadedFile.writeTo(newFile);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
				ContextRelativeResource resource = new ContextRelativeResource(path);
				tempImg = new NonCachingImage("productImg", resource); 
				UploadProductPanel.this.get("productImg").replaceWith(tempImg);
				target.add(UploadProductPanel.this);
			}
		}
	};
	
	/**
	 * Creates a new UploadProductPanel object. 
	 *
	 * @param id
	 * @param model
	 */
	@SuppressWarnings("nls")
	public UploadProductPanel(String id, IModel<Product> model) {
		super(id, model);
		setOutputMarkupId(true);
		product = model.getObject();
		LoadCategoriesOperation op = new LoadCategoriesOperation();
		op.execute();
		categoryCombo = new DropDownChoice<ProductCategory>("category",op.getCategories());
		form = new Form<Product>("pform",model);
		form.add(nameField,descriptionField,priceField,categoryCombo,fileUploadField,previewBtn,saveBtn);
		String path = PRODUCTS_PICS_PATH + product.getCode() + ".jpg";
		ContextRelativeResource resource = new ContextRelativeResource(path);
		image = new NonCachingImage("productImg", resource);
		add(form,image);
	}
	
}
